package com.pkk.cloud.support.oauth2.security.access.entrypoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pkk.components.rpc.common.code.AuthoritiesCode;
import com.pkk.components.rpc.response.util.ResponseUtil;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @Description: 用于client校验及token校验失败返回信息
 * @Author: peikunkun
 * @Date: 2020/3/21 0021 下午 4:17
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

  @Autowired
  private ObjectMapper objectMapper;

  /**
   * @Description: OAuth2AuthenticationProcessingFilter#doFilter的token验证失败异常抛出异常然后定义的返回类
   * @Param: request
   * @Param response
   * @Param authException
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/3/23 0023 上午 11:47
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException authException)
      throws IOException, ServletException {
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().write(
        objectMapper.writeValueAsString(ResponseUtil.error(AuthoritiesCode.CLIENT_VALID_TOKEN_ERROR)));
  }
}
